package com.ruoyi.mobile.api;


import com.ruoyi.common.core.domain.AjaxResults;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.qsng.domain.*;
import com.ruoyi.qsng.service.IKCheckRuleService;
import com.ruoyi.qsng.service.IKIntegralDetailedService;
import com.ruoyi.qsng.service.IKIntegralOrderService;
import com.ruoyi.qsng.service.IKMyRewardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 签到
 *
 * @author gk
 * @date 2023-06-26
 */
@Api(tags = "签到")
@RestController
@RequestMapping
public class signInController {

    @Autowired
    private IKMyRewardService kMyRewardService;

    @Autowired
    private IKCheckRuleService kCheckRuleService;

    @Autowired
    private IKIntegralOrderService kIntegralOrderService;

    @Autowired
    private IKIntegralDetailedService kIntegralDetailedService;

    /**
     * 签到
     */
    @ApiOperation(value = "签到")
    @PostMapping("/weixin/addKMyRewardService")
    @Transactional
    public AjaxResults addKMyRewardService(KMyReward kMyReward) throws ParseException {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat fmt1 = new SimpleDateFormat("yyyy-MM-dd");
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户id失败！");
        //先查询是否签到
        KMyReward kMyReward1 =new KMyReward();
        kMyReward1.setUserId(userId);
//        kMyReward1.setSignInDate(kMyReward.getSignInDate());
        kMyReward1.setSignInDate(new Date());
        kMyReward1.setDate(fmt1.format(new Date()));
        kMyReward.setUserId(userId);
        kMyReward.setSignInDate(new Date());
        List<KMyReward> kMyRewardList=kMyRewardService.selectKMyRewardListForApp(kMyReward1);
        if(kMyRewardList.size()>0){
            return AjaxResults.error("您已签到！");
        }
        //更新连续签到时长
        KMyReward kMyReward2 =new KMyReward();
        kMyReward2.setUserId(userId);
        List<KMyReward> kMyRewardList1=kMyRewardService.selectKMyRewardList(kMyReward2);
        kMyReward.setContinuous((long) 1);
        if(kMyRewardList1.size()>0){
            if(fmt.format(dateAddOne(kMyRewardList1.get(0).getSignInDate())).equals(fmt.format(new Date()))){
                kMyReward.setContinuous(kMyRewardList1.get(0).getContinuous()+1);
            }
        }

        //更新类型
        kMyReward.setType(String.valueOf(111));

        //更新奖励积分
        KCheckRule kCheckRule =new KCheckRule();
        kCheckRule.setRewardDay(kMyReward.getContinuous());
        List<KCheckRule> kCheckRuleList=kCheckRuleService.selectKCheckRuleList(kCheckRule);
        if(kCheckRuleList.size()>0){
            KMyReward kMyReward3 =kMyReward;
            kMyReward3.setType(String.valueOf(112));
            kMyReward3.setRewardIntegral(kCheckRuleList.get(0).getRewardEvery());
            kMyRewardService.insertKMyReward(kMyReward3);
            this.inserKIntegralOrder(userId,kCheckRuleList.get(0).getRewardEvery(),"连续签到奖励",2,"");

        }

        this.inserKIntegralOrder(userId,10,"签到奖励",1,"");

        //更新类型
        kMyReward.setType(String.valueOf(111));
        //奖励积分
        kMyReward.setRewardIntegral(10);
        return AjaxResults.success(kMyRewardService.insertKMyReward(kMyReward));
    }



    public void inserKIntegralOrder(Long userId,Integer score,String name,int type,String activityId){

        //增加积分 先判断有无 有修改 无新增
        KIntegralOrder kIntegralOrder =new KIntegralOrder();
        kIntegralOrder.setUserId(String.valueOf(userId));
        List<KIntegralOrder> kIntegralOrderList=kIntegralOrderService.selectKIntegralOrderList(kIntegralOrder);
        if(kIntegralOrderList.size()>0){
            kIntegralOrder.setIntegral(kIntegralOrderList.get(0).getIntegral()+score);
            kIntegralOrder.setId(kIntegralOrderList.get(0).getId());
            kIntegralOrderService.updateKIntegralOrder(kIntegralOrder);
        }else {
            kIntegralOrder.setIntegral(score);
            kIntegralOrderService.insertKIntegralOrder(kIntegralOrder);
        }

        //增加记录
        KIntegralDetailed kIntegralDetailed =new KIntegralDetailed();
        kIntegralDetailed.setUserId(String.valueOf(userId));
        kIntegralDetailed.setIntegral(score);
        kIntegralDetailed.setType(String.valueOf(type));
        kIntegralDetailed.setIntegralSource(name);
        kIntegralDetailed.setActivityId(activityId);
        kIntegralDetailedService.insertKIntegralDetailed(kIntegralDetailed);
    }

    /*日期加+1天*/
    public  Date dateAddOne(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
        date=calendar.getTime(); //这个时间就是日期往后推一天的结果
        return date;

    }

    /*日期加-1天*/
    public  Date dateDeOne(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE,-1); //把日期往后增加一天,整数  往后推,负数往前移动
        date=calendar.getTime(); //这个时间就是日期往后推一天的结果
        return date;

    }
    /**
     *  签到页面
     */
    @ApiOperation(value = "签到页面")
    @GetMapping("/weixin/onloadSignIn")
    public AjaxResults onloadSignIn() throws ParseException {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户id失败！");

        //获取连续签到天数
        HashMap<String, Object> map =new HashMap<>();
        KMyReward kMyReward2 =new KMyReward();
        kMyReward2.setUserId(userId);
        List<KMyReward> kMyRewardList1=kMyRewardService.selectKMyRewardList(kMyReward2);
        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
        if(kMyRewardList1.size()>0){
            if(fmt.format(kMyRewardList1.get(0).getSignInDate()).equals(fmt.format(new Date()))){
                map.put("day",kMyRewardList1.get(0).getContinuous());
            }else if(fmt.format(kMyRewardList1.get(0).getSignInDate()).equals(fmt.format(dateDeOne(new Date())))){
                map.put("day",kMyRewardList1.get(0).getContinuous());
            } else{
                map.put("day",0);
            }
        }else {
            map.put("day",0);
        }

        //是否签到
        KMyReward kMyReward1 =new KMyReward();
        kMyReward1.setUserId(userId);
        kMyReward1.setSignInDate(new Date());
        List<KMyReward> kMyRewardList=kMyRewardService.selectKMyRewardListForApp(kMyReward1);
        if(kMyRewardList.size()>0){
            map.put("isSignIn",true);
        }else {
            map.put("isSignIn",false);
        }

        //是否领取奖励
        KCheckRule kCheckRule =new KCheckRule();
        List<KCheckRule> kCheckRuleList=kCheckRuleService.selectKCheckRuleList(kCheckRule);

        KIntegralDetailed kIntegralDetailed =new KIntegralDetailed();
        kIntegralDetailed.setUserId(String.valueOf(userId));
        kIntegralDetailed.setIntegralSource("连续签到奖励");
        List<KIntegralDetailed>  kIntegralDetailedList=kIntegralDetailedService.selectKIntegralDetailedList(kIntegralDetailed);
        HashSet<Object> set = new HashSet<>();
        for (KIntegralDetailed  kIntegralDetailed1: kIntegralDetailedList) {
            set.add(kIntegralDetailed1.getIntegral());
        }
        for (KCheckRule kCheckRule1: kCheckRuleList) {
            kCheckRule1.setReceive(false);
            if(set.contains(kCheckRule1.getRewardEvery())){
                kCheckRule1.setReceive(true);
            }
        }
        map.put("continuous",kCheckRuleList);

        KIntegralOrder kMyReward =new KIntegralOrder();
        kMyReward.setUserId(String.valueOf(userId));
        List<KIntegralOrder> kMyRewardList2=kIntegralOrderService.selectKIntegralOrderList(kMyReward);
        map.put("jifen",kMyRewardList2.get(0).getIntegral());
        return AjaxResults.success(map);
    }



    /**
     *  查询本月签到日期
     */
    @ApiOperation(value = "查询本月签到日期")
    @GetMapping("/weixin/selectDate")
    public AjaxResults selectDate(String date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,this.getMonthSpace(sdf.format(new Date()),date) );
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        int max = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        KMyReward kMyReward =new KMyReward();
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        Assert.notNull(userId, "获取用户id失败！");
        kMyReward.setUserId(userId);
        kMyReward.setDate(date);
        List<KMyReward>  KMyRewardList  =kMyRewardService.selectKMyRewardListForMonth(kMyReward);

        HashSet<Object> set = new HashSet<>();
        for (KMyReward kMyReward1:KMyRewardList) {
            set.add(sdf.format(kMyReward1.getSignInDate()));
        }

        List<WXDate>  wxDateList =new ArrayList<>();
        for (int i = 0; i < max; i++) {
            calendar.set(Calendar.DAY_OF_MONTH, i + 1);
            String day = sdf.format(calendar.getTime());
//            System.out.println(day);
            WXDate wxDate =new WXDate();
            wxDate.setDate(day.substring(day.length()-2,day.length()));
            wxDate.setTrue(false);
            if(set.contains(day)){
                wxDate.setTrue(true);
            }
            wxDateList.add(wxDate);
        }
        return  AjaxResults.success(wxDateList);
    }

    /**
     * 获取两个日期相差多少个月
     */

    public  int getMonthSpace(String date1, String date2)
            throws ParseException {

        int result = 0;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();

        c1.setTime(sdf.parse(date1));
        c2.setTime(sdf.parse(date2));

        int i = c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR);
        int month = 0;
        if (i<0)
        {
            month = -i*12;
        }else if(i>0)
        {
            month =  i*12;
        }
        result = (c2.get(Calendar.MONDAY) - c1.get(Calendar.MONTH)) + month;

        return i< 0 ? - (result) :result;

    }
}
